package com.zkc.blog.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zkc.blog.mapper.BlogMapper;
import com.zkc.blog.pojo.Blog;
import com.zkc.blog.pojo.BlogExample;
import com.zkc.blog.service.BlogService;
import com.zkc.blog.uilt.MarkdownUnit;

@Service
public class BlogServiceImpl implements BlogService {

	@Autowired
	private BlogMapper blogMapper;
	
	@Override
	public void insertBlog(Blog record) {	
		blogMapper.insert(record);
	}

	@Override
	public void deleteBlogById(List<Integer> blogids) {	
		BlogExample ex=new BlogExample();
		ex.createCriteria().andBlogidIn(blogids);
		blogMapper.deleteByExample(ex);
	}

	@Override
	public void updateBlogById(Blog record) {
		blogMapper.updateById(record);
	}

	@Override
	public Blog getBlog(Integer blogid) {
		// TODO Auto-generated method stub
		return blogMapper.selectById(blogid);
	}

	@Override
	public List<Blog> getBlogList(String searchkey,Integer cateid) {
		// TODO Auto-generated method stub
		if(searchkey==null){
			searchkey="";
		}
		searchkey="%"+searchkey+"%";
		BlogExample ex=new BlogExample();
		if(cateid!=null && cateid>0){
			ex.createCriteria().andTitleLike(searchkey).andBlogcateidEqualTo(cateid);
		}else{
			ex.createCriteria().andTitleLike(searchkey);
		}
		return blogMapper.selectByExample(ex);
	}

	@Override
	public Blog getMarkdownBlog(Integer blogid) {
		Blog blog=blogMapper.selectById(blogid);
		if(blog!=null){
			blog.setContent(MarkdownUnit.markdownToHtmlEx(blog.getContent()));
			return blog;
		}
		return null;
	}

	@Override
	public List<Blog> getBlogListByYear(String year) {
		BlogExample ex=new BlogExample();
		if(year!=null && !year.equals("")){
			SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				Date sdate = sf.parse(year+"-01-01 00:00:00");
				Date edate=sf.parse(year+"-12-31 23:00:00");
				ex.createCriteria().andCreatetimeBetween(sdate, edate);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return blogMapper.selectByExample(ex);
	}

	@Override
	public List<String> getBlogYear() {
		// TODO Auto-generated method stub
		return blogMapper.selectBlogYear();
	}

}
